package com.zyz.sunliky.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.zyz.sunliky.mapper.hr",
        sqlSessionTemplateRef = "hrSqlSessionTemplate")
public class HRDbConfig {

    @Autowired
    @Qualifier("hrDataSource")
    private DataSource hrDataSource;

    @Bean(name = "hrSqlSessionFactory")
    public SqlSessionFactory hrSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(hrDataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/hr/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "hrTransactionManager")
    public DataSourceTransactionManager hrTransactionManager() {
        return new DataSourceTransactionManager(hrDataSource);
    }

    @Bean(name = "hrSqlSessionTemplate")
    public SqlSessionTemplate hrSqlSessionTemplate(@Qualifier("hrSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}